﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetUniLodz.Models;
using System.Web.Security;
using System.IO;

namespace DotNetUniLodz.Controllers
{
    public class ArticlesController : Controller
    {
        private DotNetULEntities db = new DotNetULEntities();

        //
        // GET: /Articles/

        public ActionResult Index()
        {
            var articles = db.Articles.Include(a => a.User);
            return View(articles.ToList().Reverse<Article>());
        }

        //
        // GET: /Articles/Details/5

        public ActionResult Details(int id = 0)
        {
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(article);
        }

        //
        // GET: /Articles/Create

        [Authorize(Roles = "Admin")]
        public ActionResult Create()
        {
            var events = db.Events.Where(e => e.Event_date > DateTime.Now);
            ViewBag.Events = new SelectList(events, "Event_id", "Event_name");

            var categories = db.Categories;
            ViewBag.Categories = new SelectList(categories, "Category_id", "Category_name");

            return View();
        }

        //
        // POST: /Articles/Create

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)] //to ma pozwolić na "Łykanie" htmla jako text
        public ActionResult Create(ArticleModel articleModel, int? EventId, int? CategoryId)
        {
            if (ModelState.IsValid)
            {
                Article article = articleModel.Article;
                article.Article_creationDate = DateTime.Now;
                article.User_author = UserModel.GetCurrentUser(User.Identity.Name).User_id;

                if (EventId != null)
                {
                    article.Event_id = EventId;
                }

                if (CategoryId != null)
                {
                    var category = db.Categories.Find(CategoryId.Value);
                    article.Categories.Add(category);
                }

                var file = Request.Files[0];
                if (file != null && file.ContentLength > 0)
                {
                    var lastFileId = db.Files.Count() > 0 ? db.Files.Max(m => m.File_id) : 0;
                    var fileName = lastFileId + Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);

                    article.File = new Models.File()
                    {
                        File_addDate = DateTime.Now,
                        File_name = fileName,
                        File_path = "Images/Uploads/" + fileName,
                        User_author = UserModel.GetCurrentUser(User.Identity.Name).User_id
                    };

                    file.SaveAs(path);
                }

                db.Articles.Add(article);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            var events = db.Events.Where(e => e.Event_date > DateTime.Now);
            ViewBag.Events = new SelectList(events, "Event_id", "Event_name", articleModel.Event_id);


            var categories = db.Categories;
            ViewBag.Categories = new SelectList(categories, "Category_id", "Category_name", articleModel.Category_id);

            return View(articleModel);
        }

        //
        // GET: /Articles/Edit/5

        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id = 0)
        {
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            var model = new ArticleModel()
            {
                Article_id = article.Article_id,
                Article_creationDate = article.Article_creationDate,
                Article_img = article.Article_img,
                Article_text = article.Article_text,
                Article_title = article.Article_title,
                Article_isMainArticle = article.Article_isMainArticle,
                Event = article.Event,
                Event_id = article.Event_id,
                File = article.File,
                Category_id = article.Category_id,
                User_author = article.User_author
            };

            var events = db.Events.Where(e => e.Event_date > DateTime.Now);
            ViewBag.Events = new SelectList(events, "Event_id", "Event_name", article.Event_id);

            var categories = db.Categories;
            var category = article.Categories.FirstOrDefault();
            if (category != null)
            {
                ViewBag.Categories = new SelectList(categories, "Category_id", "Category_name", category.Category_id);
            }
            else
            {
                ViewBag.Categories = new SelectList(categories, "Category_id", "Category_name");
            }

            return View(model);
        }

        //
        // POST: /Articles/Edit/5

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)] //to ma pozwolić na "Łykanie" htmla jako text
        public ActionResult Edit(ArticleModel articleModel, int? EventId, int? CategoryId, bool removeImg)
        {
            if (ModelState.IsValid)
            {
                Article article = db.Articles.Include("Categories").FirstOrDefault(a => a.Article_id == articleModel.Article.Article_id);

                article.Article_text = articleModel.Article.Article_text;
                article.Article_title = articleModel.Article.Article_title;
                article.Article_isMainArticle = articleModel.Article_isMainArticle;

                article.Event_id = EventId;

                if (CategoryId != null)
                {
                    var category = db.Categories.Find(CategoryId.Value);
                    category.Articles.Add(article);
                    db.Entry(category).State = EntityState.Modified;
                    article.Categories.Add(category);
                }
                else
                {
                    var categories = article.Categories.ToList();
                    categories.ForEach(c => article.Categories.Remove(c));
                }

                article.Article_lastMod = DateTime.Now;

                if (removeImg)
                {
                    article.File = null;
                    article.Article_img = null;
                }
                else
                {
                    var file = Request.Files[0];
                    if (file != null && file.ContentLength > 0)
                    {
                        var lastFileId = db.Files.Count() > 0 ? db.Files.Max(m => m.File_id) : 0;
                        var fileName = lastFileId + Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);

                        var fileModel = new Models.File()
                        {
                            Article = new List<Models.Article>() { article },
                            File_addDate = DateTime.Now,
                            File_name = fileName,
                            File_path = "Images/Uploads/" + fileName,
                            User_author = UserModel.GetCurrentUser(User.Identity.Name).User_id
                        };
                        file.SaveAs(path);
                        db.Files.Add(fileModel);
                    }
                }

                db.Entry(article).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            var events = db.Events.Where(e => e.Event_date > DateTime.Now);
            ViewBag.Events = new SelectList(events, "Event_id", "Event_name", articleModel.Event_id);

            var categories2 = db.Categories;
            ViewBag.Categories = new SelectList(categories2, "Category_id", "Category_name", articleModel.Category_id);

            return View(articleModel);
        }

        //
        // GET: /Articles/Delete/5

        [Authorize(Roles = "Admin")]
        public ActionResult Delete(int id = 0)
        {
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(article);
        }

        //
        // POST: /Articles/Delete/5

        [Authorize(Roles = "Admin")]
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Article article = db.Articles.Find(id);
            db.Articles.Remove(article);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult FromCategory(int id)
        {
            var articles = from c in db.Categories
                           where c.Category_id == id
                           select c.Articles.ToList();

            return View(articles.ToList());
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}